const { addAdmin, findAdmin } = require("../../services/adminService");

const router = require("express").Router();
router.post("/register", async (req, res) => {
  let { username, password } = req.body;
  let result = await addAdmin({ username, password });
  res.json(result);
});
router.post("/login", async (req, res) => {
  let { username, password } = req.body;
  let result = await findAdmin({ username, password });
  if (result.status === 1) {
    //说明登陆成功 给浏览器颁发一个token(设置cookie)
    //cookie 最核心的组成部分是 key-value (token=用户对应的主键id)
    res.cookie("token", result.id, {
      domain: "localhost",
      path: "/",
      maxAge: 3600 * 1000, //一个小时
    });
  }
  res.json(result);
});
//whoami
router.get("/whoami", (req, res) => {
  if (req.cookies.token) {
    //说明之前登陆过了
    res.json({
      msg: "该用户已经登陆",
      status: 1,
    });
  } else {
    res.json({
      msg: "该用户未登陆",
      status: 0,
    });
  }
});
module.exports = router;
